﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Input;

namespace SysLib
{
    public class WinAPISenkey
    {
        [DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
        private static extern void keybd_event(byte bVk, byte bScan, long dwFlags, long dwExtraInfo);

        private const byte VK_LWIN = 0x5b;
        private const byte KEYEVENTF_KEYUP = 0x2;
        private const byte VK_APPS = 0x5d;
        /// <summary>
        /// SenKey
        /// </summary>
        /// <param name="keyModify"></param>
        /// <param name="key"></param>
        public static void SenKey(ModifierKeys keyModify, Key key)
        {
            byte VK_Modify = 0x12;
            switch (keyModify)
            {
                case ModifierKeys.Alt:
                    {
                        VK_Modify = 0x12;
                        break;
                    }
                case ModifierKeys.Control:
                    {
                        VK_Modify = 0x11;
                        break;
                    }
                case ModifierKeys.Shift:
                    {
                        VK_Modify = 0x10;
                        break;
                    }
                case ModifierKeys.Windows:
                    {
                        VK_Modify = 0x5B;
                        break;
                    }
            }

            byte decValue = (byte)KeyInterop.VirtualKeyFromKey(key);

            if (keyModify != ModifierKeys.None)
                keybd_event(VK_Modify, 0, 0, 0);
            //
            keybd_event(decValue, 0, 0, 0); //VK_ACTION

            if (keyModify != ModifierKeys.None)
                keybd_event(VK_Modify, 0, KEYEVENTF_KEYUP, 0);
            keybd_event(decValue, 0, KEYEVENTF_KEYUP, 0);
        }
    }
}
